import numpy as np
 
def pagerank(M, alpha=0.85, tol=1e-6, max_iter=100):
    """
    Compute the PageRank of a matrix using the power iteration method.
 
    Parameters:
    - M: Transition probability matrix (stochastic matrix).
    - alpha: Damping factor.
    - tol: Tolerance for convergence.
    - max_iter: Maximum number of iterations.
 
    Returns:
    - r: PageRank vector.
    """
    n = M.shape[0]
    r = np.ones(n) / n  
# Initial PageRank values
    base = (1 - alpha) / n * np.ones(n)  
# Base value for random jumps
 
    for _ in range(max_iter):
        r_next = alpha * M @ r + base
        if np.linalg.norm(r_next - r, ord=1) < tol:
            return r_next
        r = r_next
    
        return r
 
# Example usage:

if __name__ == "__main__":
    
# Example transition matrix
    
# Rows represent outgoing links and columns represent incoming links.
    M = np.array([[0, 1/4, 1/3, 0, 0, 1/2, 0],
              [1/4, 0, 0, 1/5, 0, 0, 0],
              [0, 1/4, 0, 1/5, 1/4, 0, 0],
              [0, 0, 1/3, 0, 1/4, 0, 0],
              [1/4, 0, 0, 1/5, 0, 0, 0],
              [1/4, 1/4, 0, 1/5, 1/4, 0, 0],
              [1/4, 1/4, 1/3, 1/5, 1/4, 1/2, 0]])
    r = pagerank(M)
    r = r / np.sum(r)
    print("PageRank values:", r)